#line 1 "C:/Users/Toanrv/Dropbox/PIC project/Source_and_Design/Digital clock/DS1307.c"
#line 1 "c:/users/toanrv/dropbox/pic project/source_and_design/digital clock/ds1307.h"
#line 24 "c:/users/toanrv/dropbox/pic project/source_and_design/digital clock/ds1307.h"
typedef struct{
 unsigned short sec;
 unsigned short min;
 unsigned short week_day;
 unsigned short day;
 unsigned short hour;
 unsigned short month;
 unsigned short year;
} RTC_Time;

void DS1307_Init();
unsigned short DS1307_BCD2Dec(unsigned char n);
unsigned short DS1307_Dec2BCD(unsigned char n) ;

void DS1307_GetDateTime(RTC_Time *p) ;

void DS1307_LCD_Display_Time(RTC_Time *p);

void DS1307_SetDateTime(RTC_Time *p);
#line 22 "C:/Users/Toanrv/Dropbox/PIC project/Source_and_Design/Digital clock/DS1307.c"
void DS1307_Init(){

 I2C1_Init(100000);
 I2C1_Start();
 I2C1_Wr( 0xD0);
 I2C1_Wr( 0x00);

 I2C1_Stop();
}
unsigned short DS1307_BCD2Dec(unsigned short n){
 return(((( n & 0x70)>>4) * 10)+ (n & 0x0F));
}
unsigned short DS1307_Dec2BCD(unsigned short n){

 return (((n/10)<<4)+(n%10));

}

void DS1307_GetDateTime(RTC_Time *p)
 {
 I2C1_Start();
 I2C1_Wr(0xD0);
 I2C1_Wr(0x00);
 I2C1_Repeated_Start();
 I2C1_Wr(0xD1);

 p->sec = DS1307_BCD2Dec(I2C1_Rd(1));
 p->min = DS1307_BCD2Dec(I2C1_Rd(1));
 p->hour = DS1307_BCD2Dec(I2C1_Rd(1));
 p->week_day = DS1307_BCD2Dec(I2C1_Rd(1));
 p->day = DS1307_BCD2Dec(I2C1_Rd(1));
 p->month = DS1307_BCD2Dec(I2C1_Rd(1));
 p->year = DS1307_BCD2Dec(I2C1_Rd(1));
 I2C1_Stop() ;

 }

void DS1307_SetDateTime(RTC_Time *p)
 {

 I2C1_Start();
 I2C1_Wr(0xD0);
 I2C1_Wr(0x00);
 I2C1_Wr(DS1307_Dec2BCD(p->sec));
 I2C1_Wr(DS1307_Dec2BCD(p->min));
 I2C1_Wr(DS1307_Dec2BCD(p->hour));
 I2C1_Wr(DS1307_Dec2BCD(p->week_day));
 I2C1_Wr(DS1307_Dec2BCD(p->day));
 I2C1_Wr(DS1307_Dec2BCD(p->month));
 I2C1_Wr(DS1307_Dec2BCD(p->year));
 I2C1_Wr(0x80);
 I2C1_Stop();

 }

void DS1307_LCD_Display_Time(RTC_Time *p)
 {

 Lcd_Chr(1, 6, (p->day / 10) + 48);
 Lcd_Chr(1, 7, (p->day % 10) + 48);
 Lcd_Chr(1, 9, (p->month / 10) + 48);
 Lcd_Chr(1,10, (p->month % 10) + 48);
 Lcd_Chr(1,14, (p->year / 10) + 48);
 Lcd_Chr(1,15, (p->year %10) + 48);


 Lcd_Chr(2, 6, (p->hour / 10) + 48);
 Lcd_Chr(2, 7, (p->hour % 10) + 48);
 Lcd_Chr(2, 9, (p->min / 10) + 48);
 Lcd_Chr(2,10, (p->min % 10) + 48);
 Lcd_Chr(2,12, (p->sec / 10) + 48);
 Lcd_Chr(2,13, (p->sec % 10) + 48);


 }
